package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ProvinceCityDistrict;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.db.CityDBClient;
import com.hemaapp.yjnh.fragment.HomePageFragment;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.RegexUtils;
import com.hemaapp.yjnh.view.ProvinceCityDialog;
import com.hemaapp.yjnh.view.YjnhImageWay;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.download.ImageDownloader;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.XtomActivityManager;
import xtom.frame.image.load.XtomImageTask;
import xtom.frame.util.XtomBaseUtil;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 填写相关资料，申请成为田家
 * @author ZhangGuiyou
 */
public class ApplyFarmerActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_CAMERA = 0x04;
    private final static int REQUEST_ALBUM = 0x05;
    private final static int REQUEST_CUT = 0x06;

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.iv_avatar)
    ImageView ivAvatar;
    @Bind(R.id.edt_name)
    EditText edtName;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.layout_sex)
    LinearLayout layoutSex;
    @Bind(R.id.edt_mobile)
    EditText edtMobile;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.layout_address)
    LinearLayout layoutAddress;
    @Bind(R.id.layout_image)
    LinearLayout layoutImage;
    @Bind(R.id.edt_id_card)
    EditText edtIdCard;
    @Bind(R.id.layout_ID_card)
    LinearLayout layoutIDCard;
    @Bind(R.id.iv_ID_front)
    ImageView ivIDFront;
    @Bind(R.id.tv_ID_front)
    TextView tvIDFront;
    @Bind(R.id.layout_ID_front)
    FrameLayout layoutIDFront;
    @Bind(R.id.iv_ID_back)
    ImageView ivIDBack;
    @Bind(R.id.tv_ID_back)
    TextView tvIDBack;
    @Bind(R.id.layout_ID_back)
    FrameLayout layoutIDBack;
    @Bind(R.id.iv_certification_front)
    ImageView ivCertificationFront;
    @Bind(R.id.tv_certification_front)
    TextView tvCertificationFront;
    @Bind(R.id.layout_certification_front)
    FrameLayout layoutCertificationFront;
    @Bind(R.id.iv_certification_back)
    ImageView ivCertificationBack;
    @Bind(R.id.tv_certification_back)
    TextView tvCertificationBack;
    @Bind(R.id.layout_certification_back)
    FrameLayout layoutCertificationBack;

//    private String name;
    private String sex;
//    private String phone;
    private String addressStr;
//    private String idCard;
    private ProvinceCityDialog dialog;
    private YjnhImageWay imageWay;
    private int type = 0;//显示类型：1注册时完善个人信息，2注册完成后查看个人信息
    private ClientDetails details;
    private int curImg = 0;//当前打开的相机或相册是由哪个位置启动的：1头像，2身份证正面，3身份证反面，4土地证书正面，5土地证书反面
    //在上传图片阶段，用来标志当前上传的是哪一张
    private String avatar_path;//头像图片的地址
    private String id_front_path;//身份证正面照片的地址
    private String id_back_path;//身份证反面照的地址
    private String cer_front_path;//土地证书正面照片的地址
    private String cer_back_path;//土地证书反面照片的地址
    private String authid = "";//认证id
    CityDBClient cityDBClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_farmer);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA);
        } else {
            avatar_path = savedInstanceState.getString("avatar_path");
            id_front_path = savedInstanceState.getString("id_front_path");
            id_back_path = savedInstanceState.getString("id_back_path");
            cer_front_path = savedInstanceState.getString("cer_front_path");
            cer_back_path = savedInstanceState.getString("cer_back_path");
            imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA);
        }
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, albumRequestCode);
            }
        };
        if (details != null) {
            layoutImage.setVisibility(View.GONE);
            setData();
        }
        //获取所有的城市
        cityDBClient = new CityDBClient(mContext);
        if (cityDBClient.getDataCount() == 0) {
            getNetWorker().getDistrictList("-2");
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (imageWay != null) {
            outState.putString("avatar_path", imageWay.getCameraImage());
            outState.putString("id_front_path", id_front_path);
            outState.putString("id_back_path", id_back_path);
            outState.putString("cer_front_path", cer_front_path);
            outState.putString("cer_back_path", cer_back_path);
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case AUTH_SAVE:
            case CLIENT_SAVE:
            case FILE_UPLOAD:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case AUTH_SAVE:
            case FILE_UPLOAD:
            case CLIENT_SAVE:
                cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case AUTH_SAVE:
                HemaArrayResult<String> tResult = (HemaArrayResult<String>) baseResult;
                authid = tResult.getObjects().get(0);
                if (!isNull(avatar_path)) {
                    curImg = 1;
                    fileUpload();
                }
                break;
            case FILE_UPLOAD:
                if (type == 1 && curImg < 6) {//申请田家，而且土地证等信息没有上传时继续上传
                    fileUpload();
                } else {
                    if (type == 1)
                        showTextDialog("申请成功");
                    else if (type == 2)
                        showTextDialog("保存成功");
                    else
                        showTextDialog("操作成功");
                    getNetWorker().clientLogin();
                }
                break;
            case CLIENT_SAVE:
                XtomToastUtil.showShortToast(mContext, "保存成功");
                if (!isNull(avatar_path)) {
                    getNetWorker().fileUpload(getApplicationContext().getUser().getToken(),
                            "1", "0", "0", "0", "无", avatar_path);
                } else {
                    getNetWorker().clientLogin();
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1500);
                }
                break;
            case CLIENT_LOGIN:
                HemaArrayResult<User> uResult = (HemaArrayResult<User>) baseResult;
                User user = uResult.getObjects().get(0);
                getApplicationContext().setUser(user);
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.USER);
                msg.setUser(user);
                EventBus.getDefault().post(msg);
                finish();
                break;
            case DISTRICT_LIST:
                HemaPageArrayResult<ProvinceCityDistrict> result = (HemaPageArrayResult<ProvinceCityDistrict>) baseResult;
                ArrayList<ProvinceCityDistrict> districts = result.getObjects();
                if (districts != null && districts.size() > 0) {
                    new SaveDistrictTask().execute(districts);
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case AUTH_SAVE:
                showTextDialog("提交失败,"+baseResult.getMsg());
                break;
            case FILE_UPLOAD:
                showTextDialog("图片上传失败");
                break;
            case CLIENT_LOGIN:
                finish();
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case AUTH_SAVE:
                showTextDialog("提交失败！");
                break;
            case FILE_UPLOAD:
                showTextDialog("图片上传失败");
                break;
            case CLIENT_LOGIN:
                finish();
                break;
        }
    }

    /**
     * 上传多张照片
     */
    private void fileUpload() {
        User user = getApplicationContext().getUser();
        String token = user.getToken();
        switch (curImg) {
            case 1:
                getNetWorker().fileUpload(token, "15", authid, "0", "0", "无", avatar_path);
                break;
            case 2:
                getNetWorker().fileUpload(token, "11", authid, "0", "0", "无", id_front_path);
                break;
            case 3:
                getNetWorker().fileUpload(token, "12", authid, "0", "0", "无", id_back_path);
                break;
            case 4:
                getNetWorker().fileUpload(token, "13", authid, "0", "0", "无", cer_front_path);
                break;
            case 5:
                getNetWorker().fileUpload(token, "14", authid, "0", "0", "无", cer_back_path);
                break;
            default:
                break;
        }
        curImg++;
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        type = getIntent().getIntExtra("type", 0);
        details = (ClientDetails) getIntent().getSerializableExtra("client");
    }

    @Override
    protected void setListener() {
        if (type == 1) {
            titleText.setText("田家认证");
        } else {
            titleText.setText("修改资料");
        }
        titleRightBtn.setText("提交");
    }

    private void setData() {
        sex = details.getSex();
        addressStr = details.getAddress();

        ImageUtils.loadAvatar(mContext, details.getAvatar(), ivAvatar);
        tvSex.setText(details.getSex());
        edtMobile.setText(details.getMobile());
        tvAddress.setText(details.getAddress());
        edtName.setText(details.getNickname());
        edtName.setSelection(details.getNickname().length());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片完成后的处理
                album(data);
                break;
            case REQUEST_CAMERA:// 拍照完成后的处理
                camera();
                break;
            case REQUEST_CUT:// 头像裁剪完成后裁剪为圆形
//                ImageUtils.loadLocalImage(mContext, avatar_path, ivAvatar);
                String imageUrl = ImageDownloader.Scheme.FILE.wrap(avatar_path);
                ImageLoader.getInstance().displayImage(imageUrl, ivAvatar, ImageUtils.avatarImageOptions);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void camera() {
        switch (curImg) {
            case 1:
                avatar_path = imageWay.getCameraImage();
                editImage(avatar_path, REQUEST_CUT);
                break;
            case 2:
                id_front_path = imageWay.getCameraImage();
                new CompressPicTask().execute(id_front_path);
                break;
            case 3:
                id_back_path = imageWay.getCameraImage();
                new CompressPicTask().execute(id_back_path);
                break;
            case 4:
                cer_front_path = imageWay.getCameraImage();
                new CompressPicTask().execute(cer_front_path);
                break;
            case 5:
                cer_back_path = imageWay.getCameraImage();
                new CompressPicTask().execute(cer_back_path);
                break;
            default:
                break;
        }
    }

    private void editImage(String path, int requestCode) {
        File file = new File(path);
        startPhotoZoom(Uri.fromFile(file), requestCode);
    }

    private void album(Intent data) {
        if (data == null)
            return;
        String picturePath = null;
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(mContext, "抱歉，没有找到图片", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(mContext, "抱歉，没有找到图片", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            picturePath = file.getAbsolutePath();
        }

        switch (curImg) {
            case 1:
                avatar_path = picturePath;
                editImage(avatar_path, REQUEST_CUT);
                break;
            case 2:
                id_front_path = picturePath;
                new CompressPicTask().execute(id_front_path);
                break;
            case 3:
                id_back_path = picturePath;
                new CompressPicTask().execute(id_back_path);
                break;
            case 4:
                cer_front_path = picturePath;
                new CompressPicTask().execute(cer_front_path);
                break;
            case 5:
                cer_back_path = picturePath;
                new CompressPicTask().execute(cer_back_path);
                break;
            default:
                break;
        }
    }

    private void startPhotoZoom(Uri uri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", BaseConfig.IMAGE_WIDTH);
        intent.putExtra("aspectY", BaseConfig.IMAGE_WIDTH);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", BaseConfig.IMAGE_WIDTH);
        intent.putExtra("outputY", BaseConfig.IMAGE_WIDTH);
        intent.putExtra("return-data", false);
        startActivityForResult(intent, requestCode);
    }

    private Uri getTempUri() {
        return Uri.fromFile(getTempFile());
    }

    private File getTempFile() {
        String savedir = XtomFileUtil.getTempFileDir(mContext);
        File dir = new File(savedir);
        if (!dir.exists())
            dir.mkdirs();
        // 保存入sdCard
        avatar_path = savedir + XtomBaseUtil.getFileName() + ".jpg";// 保存路径
        File file = new File(avatar_path);
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        return file;
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn, R.id.iv_avatar, R.id.layout_sex,
            R.id.layout_address, R.id.layout_ID_card, R.id.layout_ID_front,
            R.id.layout_ID_back, R.id.layout_certification_front, R.id.layout_certification_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                String name = edtName.getText().toString().trim();
                String phone = edtMobile.getText().toString().trim();
                String idCard = edtIdCard.getText().toString().trim();
                if (isNull(name)) {
                    showTextDialog("请输入姓名!");
                    break;
                } else if (isNull(sex)) {
                    showTextDialog("请选择性别!");
                    break;
                } else if (isNull(phone)) {
                    showTextDialog("请输入电话号码");
                    break;
                } else if (!RegexUtils.judgeMobile(phone)) {
                    showTextDialog("电话号码输入不正确");
                    break;
                } else if (isNull(addressStr)) {
                    showTextDialog("请选择地址!");
                    break;
                }
                if (type == 1) {
                    if (isNull(idCard)) {
                        showTextDialog("请输入身份证号码");
                    } else if (!RegexUtils.judgeIdNum(idCard)) {
                        showTextDialog("请输入有效身份证号");
                    } else if (isNull(avatar_path)) {
                        showTextDialog("请选择头像!");
                    } else if (isNull(id_front_path)) {
                        showTextDialog("请选择身份证正面照片!");
                    } else if (isNull(id_back_path)) {
                        showTextDialog("请选择身份证反面照片!");
                    } else if (isNull(cer_front_path)) {
                        showTextDialog("请选择土地证书正面照片!");
                    } else if (isNull(cer_back_path)) {
                        showTextDialog("请选择土地证书反面照片!");
                    } else {
                        getNetWorker().applyFarmer(getApplicationContext().getUser().getToken(),
                                name, sex, addressStr, phone, idCard);
                    }
                } else {
                    getNetWorker().clientSave(getApplicationContext().getUser().getToken(),
                            name, sex, phone, addressStr);
                }
                break;
            case R.id.iv_avatar:
                curImg = 1;
                showPic();
                break;
            case R.id.layout_sex:
                showSex();
                break;
            case R.id.layout_address:
                if (dialog == null) {
                    dialog = new ProvinceCityDialog(mContext).builder();
                    dialog.setListener(new ProvinceCityDialog.onSelectedItemListener() {
                        @Override
                        public void onSelected(int province, int city, int county) {
                            String provinceStr = "";
                            String cityStr = "";
                            String countyStr = "";
//                            if (province == 0)
//                                provinceStr = "全国";
//                            else
//                                provinceStr = dialog.getProvinceDatas().get(province);
//                            if (city != 0) {
//                                cityStr = dialog.getCityDatas().get(city);
//                                if (county != 0) {
//                                    countyStr = dialog.getCountyDatas().get(county);
//                                    addressStr = provinceStr + cityStr + countyStr;
//                                } else {
//                                    addressStr = provinceStr + cityStr;
//                                }
//                            } else {
//                                addressStr = provinceStr;
//                            }
//                            tvAddress.setText(addressStr);
                            provinceStr = dialog.getProvinceDatas().get(province);
                            cityStr = dialog.getCityDatas().get(city);
                            countyStr = dialog.getCountyDatas().get(county);
                            if (cityStr.equals("暂无"))
                                cityStr = "";
                            if (countyStr.equals("暂无"))
                                countyStr = "";
                            addressStr = provinceStr + cityStr + countyStr;
                            tvAddress.setText(addressStr);
                        }
                    });
                }
                dialog.show();
                break;
            case R.id.layout_ID_card:
                break;
            case R.id.layout_ID_front:
                curImg = 2;
                showPic();
                break;
            case R.id.layout_ID_back:
                curImg = 3;
                showPic();
                break;
            case R.id.layout_certification_front:
                curImg = 4;
                showPic();
                break;
            case R.id.layout_certification_back:
                curImg = 5;
                showPic();
                break;
        }
    }

    /**
     * 显示图片选择对话
     */
    public void showPic() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                imageWay.camera();
                            }
                        })
                .addSheetItem("从相册打开", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                imageWay.album();
                            }
                        })
                .show();
    }

    /**
     * 显示性别选择对话
     */
    public void showSex() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("男", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                sex = "男";
                                tvSex.setText(sex);
                            }
                        })
                .addSheetItem("女", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                sex = "女";
                                tvSex.setText(sex);
                            }
                        })
                .show();
    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0://压缩成功
                    if (curImg == 2) {
                        id_front_path = compressPath;
                        ivIDFront.setVisibility(View.VISIBLE);
                        tvIDFront.setVisibility(View.GONE);
//                        Glide.with(mContext).load(compressPath).centerCrop().into(ivIDFront);
                        ImageUtils.loadLocalImage(mContext, compressPath, ivIDFront);
                    } else if (curImg == 3) {
                        id_back_path = compressPath;
                        ivIDBack.setVisibility(View.VISIBLE);
                        tvIDBack.setVisibility(View.GONE);
//                        Glide.with(mContext).load(compressPath).centerCrop().into(ivIDBack);
                        ImageUtils.loadLocalImage(mContext, compressPath, ivIDBack);
                    } else if (curImg == 4) {
                        cer_front_path = compressPath;
                        ivCertificationFront.setVisibility(View.VISIBLE);
                        tvCertificationFront.setVisibility(View.GONE);
//                        Glide.with(mContext).load(compressPath).centerCrop().into(ivCertificationFront);
                        ImageUtils.loadLocalImage(mContext, compressPath, ivCertificationFront);
                    } else if (curImg == 5) {
                        cer_back_path = compressPath;
                        ivCertificationBack.setVisibility(View.VISIBLE);
                        tvCertificationBack.setVisibility(View.GONE);
//                        Glide.with(mContext).load(compressPath).centerCrop().into(ivCertificationBack);
                        ImageUtils.loadLocalImage(mContext, compressPath, ivCertificationBack);
                    }
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }

    private class ImageTask extends XtomImageTask {

        public ImageTask(ImageView imageView, String path, Object context,
                         Size size) {
            super(imageView, path, context, size);
        }

        public ImageTask(ImageView imageView, URL url, Object context, Size size) {
            super(imageView, url, context, size);
        }

        @Override
        public void setBitmap(Bitmap bitmap) {
            bitmap = XtomImageUtil.getRoundedCornerBitmap(bitmap, 500);
            super.setBitmap(bitmap);
        }
    }

    private class SaveDistrictTask extends AsyncTask<ArrayList<ProvinceCityDistrict>, Void, Void> {

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在保存");
        }

        @Override
        protected Void doInBackground(ArrayList<ProvinceCityDistrict>... params) {
            cityDBClient.clear();
            for (ProvinceCityDistrict district : params[0]) {
                cityDBClient.insert(district);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            cancelProgressDialog();
        }
    }
}
